from PyQt5 import QtCore, QtGui, QtWidgets
import sys, base64, sip
import qtawesome, requests, re,random
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor, QImage, QPixmap
from PyQt5.QtWidgets import QColorDialog,QFontDialog
from io import BytesIO
from PyQt5 import QtWidgets, QtCore
import sys
from PyQt5.QtCore import *
import time
import threading

class Runthread(QtCore.QThread):
    #  通过类成员对象定义信号对象
    _signal = pyqtSignal(str)

    def __init__(self):
        super(Runthread, self).__init__()

    def __del__(self):
        self.wait()

    def run(self):
        for i in range(101):
            time.sleep(0.2)
            self._signal.emit(str(i))  # 注意这里与_signal = pyqtSignal(str)中的类型相同


class MainUi(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.pags=[]
        self.select_imag_url=[]
        self.select_iico=[]
        self.size_L,self.weight_L,self.family_L,self.color_L,self.num = '18','75','Helvetica Neue','#a0a0a4','9'
        self.size_R,self.weight_R,self.family_R,self.color_R = '15','600','Helvetica Neue','rgb(247, 247, 247)'
        self.right_img_get()
        self.init_ui()


    def start_login(self):
        # 创建线程
        self.thread = Runthread()
        # 连接信号
        self.thread._signal.connect(self.print_111)  # 进程连接回传到GUI的事件
        # 开始线程
        self.thread.start()
    def print_111(self):
        print('111111')
    def pag_back(self,pags):
        self.main_layout.removeWidget(pags)
        sip.delete(pags)

    def right_secede_ui(self):
        self.right_secede_widget = QtWidgets.QWidget()  # 创建右侧部件
        self.right_secede_widget.setObjectName('right_widget')
        self.right_secede_layout = QtWidgets.QGridLayout()
        self.right_secede_widget.setLayout(self.right_secede_layout)  # 设置右侧部件布局为网格
        self.main_layout.addWidget(self.right_secede_widget, 0, 16, 30, 80)  # 右侧部件在第0行第3列，占8行9列
        self.right_secede_widget.setStyleSheet('''
                                QWidget#right_secede_widget{
                                color:#232C51;
                                background:white;
                                border-top:1px solid darkGray;
                                border-bottom:1px solid darkGray;
                                border-right:1px solid darkGray;
                                border-top-right-radius:10px;
                                border-bottom-right-radius:10px;
                                }
                                ''')
    def right_base_ui(self):
        self.right_widget = QtWidgets.QWidget()  # 创建右侧部件
        self.right_widget.setObjectName('right_widget')
        self.right_layout = QtWidgets.QGridLayout()
        self.right_widget.setLayout(self.right_layout)  # 设置右侧部件布局为网格

        self.right_bar_widget = QtWidgets.QWidget()  # 右侧顶部搜索框部件
        self.right_bar_layout = QtWidgets.QGridLayout()  # 右侧顶部搜索框网格布局
        self.right_bar_widget.setLayout(self.right_bar_layout)
        self.main_layout.addWidget(self.right_widget, 0, 16, 30, 80)  # 右侧部件在第0行第3列，占8行9列

        self.right_book_read_widget = QtWidgets.QWidget()  # 推荐封面部件
        self.right_book_read_layout = QtWidgets.QGridLayout()  # 推荐封面网格布局
        self.right_book_read_widget.setLayout(self.right_book_read_layout)

        self.right_book_read_widget_button = QtWidgets.QWidget()  # 推荐封面部件
        self.right_book_read_layout_button = QtWidgets.QGridLayout()  # 推荐封面网格布局
        self.right_book_read_widget_button.setLayout(self.right_book_read_layout_button)

        self.right_widget.setStyleSheet('''
                                QWidget#right_widget{
                                color:#232C51;
                                background:white;
                                border-top:1px solid darkGray;
                                border-bottom:1px solid darkGray;
                                border-right:1px solid darkGray;
                                border-top-right-radius:10px;
                                border-bottom-right-radius:10px;
                                }
                                ''')
    def thread_it(self,func):
        t = threading.Thread(target=func)
        t.setDaemon(True)
        t.start()

    def re_select(self,book_name):
        self.all = []
        with open('proxy.conf', 'r', encoding='utf8') as IP_L:
                A_L = IP_L.read()
        ip_list = re.findall(r"'(.*?)','(.*?)'", A_L, re.S)
        IP_L.close()

        proxy_ip = random.choice(ip_list)
        ppp = "http://%s:%s" % (proxy_ip[0], proxy_ip[1])
        ppps = "https://%s:%s" % (proxy_ip[0], proxy_ip[1])
        proxies = {'http': ppp, 'https': ppps}
        print(proxies)
        url = 'https://www.qidian.com/search?kw=%s'%book_name
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36'}
        book_select = requests.get(url, headers=headers, proxies=proxies)
        html = book_select.text
        self.select_book_name = re.findall(r'<div class="book-mid-info">[\s\S.].*?<h4><a href="(.*?)" target=.*?><cite class="red-kw">(.*?)</cite>(.*?)</a></h4>[\s\S.].*?<p class="author">',html, re.S)
        self.select_book_imag = re.findall(r'<div class="book-img-box">[\s\S.]*?<img src="(.*?)"></a>[\s\S.]*?</div>*?[\s\S.]*?</li>',html, re.S)
        self.select_book_author = re.findall(r'<p class="author">[\s\S.].*?target="_blank">(.*?)</a>.*? target="_blank">(.*?)</a><em>\|</em><span>(.*?)</span>',html, re.S)
        self.select_book_value = re.findall(r'<p class="intro">[\s\S.]                                   (.*?)[\s\S.]                               [\s\S.]</p>[\s\S.].*?[\s\S.]<p class="update">',html, re.S)
        self.select_book_laster = re.findall(r'<p class="update"><a href=".*?" target="_blank" data-eid=".*?" data-bid=".*?" data-cid=".*?">最新更新  (.*?)</a><em>.*?</em><span>(.*?)</span>',html, re.S)
        self.select_book_stat = re.findall(r'<div class="book-right-info">[\s\S.].*?<div class="total">[\s\S.].*?<p><span> (.*?)</span>总字数</p>[\s\S.].*?<p><span> (.*?)</span>总推荐</p>[\s\S.].*?</div>',html, re.S)
        self.select_imag_url=[]
        self.select_iico=[]
        for i in self.select_book_imag:
            i = 'https:' + i
            self.select_imag_url.append(i)

        for url in self.select_imag_url:
            req = requests.get(url)
            self.select_iico.append(req.content)
        for select_book_name, select_book_img, select_book_author, select_book_value, select_book_laster, select_book_stat,select_book_num in zip(self.select_book_name, self.select_book_imag, self.select_book_author, self.select_book_value, self.select_book_laster, self.select_book_stat,range(len(self.select_book_name))):
            cmd = "right_select_result_img_%s=QtWidgets.QToolButton()" % select_book_num
            exec(cmd)
            #locals()['right_select_result_img_%s'%select_book_num].setText(select_book_name[1]+select_book_name[2].replace('<cite class="red-kw">', '').replace('</cite>', ''))  # 设置按钮文本
            locals()['right_select_result_img_%s'%select_book_num].setText(str(select_book_num))  # 设置按钮文本
            locals()['right_select_result_img_%s'%select_book_num].setIcon(self.ico(self.select_iico[int(select_book_num)]))  # 设置按钮图标
            locals()['right_select_result_img_%s'%select_book_num].setIconSize(QtCore.QSize(150, 150))  # 设置图标大小
            locals()['right_select_result_img_%s'%select_book_num].setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)  # 设置按钮形式为上图下文
            locals()['right_select_result_img_%s'%select_book_num].setFont(QtGui.QFont('SansSerif', 10))
            locals()['right_select_result_img_%s'%select_book_num].setToolTip(select_book_name[1]+select_book_name[2])
            self.right_select_result_layout.addWidget(locals()['right_select_result_img_%s' % select_book_num], 10*int(select_book_num), 0,7,3)

            Name = select_book_name[1] + select_book_name[2].replace('<cite class="red-kw">', '').replace('</cite>', '')
            Author = select_book_author[0]
            Type = select_book_author[1]
            Stat = select_book_author[2]
            Fonz = select_book_stat[0]
            Tj = select_book_stat[1]

            select_result_book_name = "right_select_label_book_name_%s=QtWidgets.QLabel('书名:%s')" % (
            select_book_num, Name)
            exec(select_result_book_name)
            locals()['right_select_label_book_name_%s' % select_book_num].setObjectName('book_label')

            select_result_book_author = "right_select_label_book_author_%s=QtWidgets.QLabel('作者:%s')" % (
            select_book_num, Author)
            exec(select_result_book_author)
            locals()['right_select_label_book_author_%s' % select_book_num].setObjectName('book_label')

            select_result_book_type = "right_select_label_book_type_%s=QtWidgets.QLabel('分类:%s')" % (
            select_book_num, Type)
            exec(select_result_book_type)
            locals()['right_select_label_book_type_%s' % select_book_num].setObjectName('book_label')

            select_result_book_stat = "right_select_label_book_stat_%s=QtWidgets.QLabel('状态:%s')" % (
            select_book_num, Stat)
            exec(select_result_book_stat)
            locals()['right_select_label_book_stat_%s' % select_book_num].setObjectName('book_label')

            select_result_book_fonz = "right_select_label_book_fonz_%s=QtWidgets.QLabel('字数:%s')" % (
            select_book_num, Fonz)
            exec(select_result_book_fonz)
            locals()['right_select_label_book_fonz_%s' % select_book_num].setObjectName('book_label')

            select_result_book_tj = "right_select_label_book_tj_%s=QtWidgets.QLabel('推荐票:%s')" % (select_book_num, Tj)
            exec(select_result_book_tj)
            locals()['right_select_label_book_tj_%s' % select_book_num].setObjectName('book_label')
            self.right_select_label_book_1=QtWidgets.QLabel('')
            self.right_select_label_book_2=QtWidgets.QLabel('')

            self.right_select_result_layout.addWidget(locals()['right_select_label_book_name_%s' % select_book_num], 10*int(select_book_num), 3,1,3 ,Qt.AlignLeft)
            self.right_select_result_layout.addWidget(locals()['right_select_label_book_author_%s' % select_book_num], 10*int(select_book_num)+1, 3,1,3, Qt.AlignLeft)
            self.right_select_result_layout.addWidget(locals()['right_select_label_book_type_%s' % select_book_num], 10*int(select_book_num)+2, 3,1,3, Qt.AlignLeft)
            self.right_select_result_layout.addWidget(locals()['right_select_label_book_stat_%s' % select_book_num], 10*int(select_book_num)+3, 3,1,3, Qt.AlignLeft)
            self.right_select_result_layout.addWidget(locals()['right_select_label_book_fonz_%s' % select_book_num], 10*int(select_book_num)+4, 3,1,3, Qt.AlignLeft)
            self.right_select_result_layout.addWidget(locals()['right_select_label_book_tj_%s' % select_book_num], 10*int(select_book_num)+5, 3,1,3, Qt.AlignLeft)
            self.right_select_result_layout.addWidget(self.right_select_label_book_1, 10*int(select_book_num)+6, 3,1,15, Qt.AlignLeft)
            self.right_select_result_layout.addWidget(self.right_select_label_book_2, 10*int(select_book_num)+7, 3,1,15, Qt.AlignLeft)


            locals()['right_select_result_img_%s' % select_book_num].clicked.connect(lambda: self.right_book_ui_select(book_num=(self.sender().text())))

            value=['%s'%(select_book_name[1]+select_book_name[2].replace('<cite class="red-kw">', '').replace('</cite>', '')),'%s'%select_book_author[0],'%s'%select_book_author[1],'%s'%select_book_author[2],'%s'%select_book_stat[0],'%s'%select_book_stat[1],'%s'%select_book_value.replace('<cite class="red-kw">', '').replace('</cite>', ''),'%s'%select_book_laster[0],'%s'%select_book_laster[1]]
            print(value)
            self.all.append(value)
        self.right_select_label_book_3 = QtWidgets.QLabel('')
        self.right_select_result_layout.addWidget(self.right_select_label_book_3, 0, 15,8*int(len(self.select_book_name)),1, Qt.AlignRight)



    def select(self):
        self.right_bar_widget_search_input_textget=self.right_bar_widget_search_input.text()

        self.right_select_result_widget = QtWidgets.QWidget()  # 创建右侧部件
        self.right_select_result_widget.setObjectName('right_set_widget')
        self.right_select_result_layout = QtWidgets.QGridLayout()
        self.right_select_result_widget.setLayout(self.right_select_result_layout)  # 设置右侧部件布局为网格
        self.right_select_result_widget.setMinimumSize(700, 2000)
        self.right_select_result_scroll = QtWidgets.QScrollArea()
        self.right_select_result_scroll.setWidget(self.right_select_result_widget)

        self.right_select_result_vbox=QtWidgets.QVBoxLayout()
        self.right_select_result_vbox.addWidget(self.right_select_result_scroll)

        #self.right_select_layout.addWidget(self.right_select_result_widget, 0, 0, 25, 40)  # 右侧部件在第0行第3列，占8行9列
        self.right_select_widget.setLayout(self.right_select_result_vbox)
        self.right_select_result_widget.setStyleSheet('''
                                                QToolButton{border:none;}
                                                QToolButton:hover{border-bottom:2px solid #F76677;}
                                                QWidget#right_select_result_widget{
                                                background:#717174;
                                                border-top:1px solid darkGray;
                                                border-bottom:1px solid darkGray;
                                                border-right:1px solid darkGray;
                                                border-left:1px solid darkGray;
                                                border-top-right-radius:10px;
                                                }
                                                ''')

        #self.right_select_jieshao = QtWidgets.QTextEdit()
        #self.right_select_jieshao.setObjectName('right_bar_widget_jieshao')
        #self.right_select_jieshao.setReadOnly(True)
        #self.right_select_result_layout.addWidget(self.right_select_jieshao, 0,0, 20, 40)


        if self.right_bar_widget_search_input_textget == '':
            var = ('查找失败，未输入关键字' + '\n')
            print(var)
        else:
            self.re_select(self.right_bar_widget_search_input_textget)

    def save_1(self):
        self.right_select_widget = QtWidgets.QWidget()  # 创建右侧部件
        self.right_select_widget.setObjectName('right_select_widget')
        self.right_select_layout = QtWidgets.QGridLayout()
        #self.right_select_widget.setLayout(self.right_select_layout)  # 设置右侧部件布局为网格
        self.right_layout.addWidget(self.right_select_widget, 1, 0, 28, 15)  # 右侧部件在第0行第3列，占8行9列
        self.right_select_widget.setStyleSheet('''
                                        QWidget#right_select_widget{
                                        color:#232C51;
                                        background:white;
                                        border-top:1px solid darkGray;
                                        border-bottom:1px solid darkGray;
                                        border-right:1px solid darkGray;
                                        border-top-right-radius:10px;
                                        border-bottom-right-radius:10px;
                                        }
                                        ''')

        self.select()



    def right_search_ui(self):
        self.search_icon = QtWidgets.QLabel(chr(0xf002) + ' ' + '搜索 ')
        self.search_icon.setFont(qtawesome.font('fa', 16))
        self.right_bar_widget_search_input = QtWidgets.QLineEdit()
        self.right_bar_widget_search_input.setPlaceholderText("输入书名或作者，回车进行搜索")
        self.right_bar_layout.addWidget(self.search_icon, 0, 0, 1, 1)
        self.right_bar_layout.addWidget(self.right_bar_widget_search_input, 0, 1, 1, 8)
        self.right_layout.addWidget(self.right_bar_widget, 0, 0, 1, 9)
        self.right_bar_widget_search_input.returnPressed.connect(self.save_1)

        self.right_bar_widget_search_input.setStyleSheet(
            '''QLineEdit{
            border:1px solid gray;
            width:300px;
            border-radius:10px;
            padding:2px 4px;
            }''')

    def clean_all(self):
        self.main_layout.removeWidget(self.right_widget)
        sip.delete(self.right_widget)
        self.right_base_ui()
        self.right_search_ui()

    def clean_search(self):
        self.main_layout.removeWidget(self.right_widget)
        sip.delete(self.right_widget)
        self.right_base_ui()

    def slot_max_or_recv(self):
        if self.isMaximized():
            self.showNormal()
        else:
            self.showMaximized()

    def mime_left_list(self):
        self.main_layout.removeWidget(self.left_widget)
        sip.delete(self.left_widget)

        self.left_widget_mime = QtWidgets.QWidget()  # 创建左侧部件
        self.left_widget_mime.setObjectName('left_widget_mime')
        self.left_layout_mime = QtWidgets.QGridLayout()  # 创建左侧部件的网格布局层
        self.left_widget_mime.setLayout(self.left_layout_mime)  # 设置左侧部件布局为网格

        self.main_layout.addWidget(self.left_widget_mime, 0, 0, 30, 1)

        self.left_button_mime = QtWidgets.QPushButton(qtawesome.icon('fa.caret-right', color='white'), "")
        self.left_button_mime.setObjectName('left_button')
        self.left_button_mime.setIconSize(QtCore.QSize(15, 30))
        self.left_layout_mime.addWidget(self.left_button_mime, 16, 0, 30, 1)
        self.left_button_mime.clicked.connect(self.max_left_list)

        self.left_widget_mime.setStyleSheet('''QPushButton{border:none;color:white;height:700px;weight:5;}
                        QPushButton#left_button:hover{border-left:2px solid white;font-weight:700;}
                        QWidget#left_widget_mime{
                        background:%s;
                        border-top:1px solid white;
                        border-bottom:1px solid white;
                        border-left:1px solid white;
                        border-top-left-radius:10px;
                        border-bottom-left-radius:10px;
                        }
                        '''%self.color_L)

    def max_left_list(self):
        self.main_layout.removeWidget(self.left_widget_mime)
        sip.delete(self.left_widget_mime)
        self.left_base_ui()

    def left_base_ui(self):
        self.left_widget = QtWidgets.QWidget()  # 创建左侧部件
        self.left_widget.setObjectName('left_widget')
        self.left_layout = QtWidgets.QGridLayout()  # 创建左侧部件的网格布局层
        self.left_widget.setLayout(self.left_layout)  # 设置左侧部件布局为网格
        self.main_layout.addWidget(self.left_widget, 0, 0, 30, 16)  # 左侧部件在第0行第0列，占8行3列

        self.left_close = QtWidgets.QPushButton("×")  # 关闭按钮
        self.left_visit = QtWidgets.QPushButton("□")  # 空白按钮
        self.left_mini = QtWidgets.QPushButton("-")  # 最小化按钮

        self.left_close.clicked.connect(self.close)
        self.left_mini.clicked.connect(self.showMinimized)
        self.left_visit.clicked.connect(self.slot_max_or_recv)

        self.left_label_1 = QtWidgets.QPushButton("每日推荐")
        self.left_label_1.setObjectName('left_label')
        self.left_label_2 = QtWidgets.QPushButton("我的书籍")
        self.left_label_2.setObjectName('left_label')
        self.left_label_3 = QtWidgets.QPushButton("联系与帮助")
        self.left_label_3.setObjectName('left_label')
        self.left_button_1 = QtWidgets.QPushButton(qtawesome.icon('fa.book', color='white'), "起点")
        self.left_button_1.setObjectName('left_button')
        self.left_button_2 = QtWidgets.QPushButton(qtawesome.icon('fa.book', color='white'), "纵横")
        self.left_button_2.setObjectName('left_button')

        self.left_button_3 = QtWidgets.QPushButton(qtawesome.icon('fa.home', color='white'), "")
        self.left_button_3.setObjectName('left_button')

        self.left_button_4 = QtWidgets.QPushButton(qtawesome.icon('fa.home', color='white'), "本地书籍")
        self.left_button_4.setObjectName('left_button')
        self.left_button_5 = QtWidgets.QPushButton(qtawesome.icon('fa.download', color='white'), "下载管理")
        self.left_button_5.setObjectName('left_button')
        self.left_button_6 = QtWidgets.QPushButton(qtawesome.icon('fa.heart', color='white'), "我的收藏")
        self.left_button_6.setObjectName('left_button')
        self.left_button_6.clicked.connect(self.left_color_select)
        self.left_button_8 = QtWidgets.QPushButton(qtawesome.icon('fa.cog', color='white'), "设置")
        self.left_button_8.setObjectName('left_button')
        self.left_button_9 = QtWidgets.QPushButton(qtawesome.icon('fa.caret-left', color='white'), "")
        self.left_button_9.setObjectName('left_button')

        self.left_xxx = QtWidgets.QPushButton(" ")

        self.left_button_1.clicked.connect(self.clean_all)
        self.left_button_1.clicked.connect(self.right_ui)

        self.left_layout.addWidget(self.left_mini, 0, 0, 1, 1)
        self.left_layout.addWidget(self.left_visit, 0, 1, 1, 1)
        self.left_layout.addWidget(self.left_close, 0, 2, 1, 1)
        self.left_layout.addWidget(self.left_button_3, 2, 0, 1, 3)
        self.left_layout.addWidget(self.left_label_1, 3, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_1, 4, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_2, 5, 0, 1, 3)
        self.left_layout.addWidget(self.left_label_2, 6, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_4, 7, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_5, 8, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_6, 9, 0, 1, 3)
        self.left_layout.addWidget(self.left_label_3, 10, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_8, 11, 0, 1, 3)
        self.left_layout.addWidget(self.left_button_9, 12, 0, 1, 3)
        self.left_button_3.clicked.connect(self.clean_all)
        self.left_button_8.clicked.connect(self.set_tools_win)
        self.left_button_9.clicked.connect(self.mime_left_list)
        self.left_button_3.setIconSize(QtCore.QSize(25, 25))
        self.left_button_9.setIconSize(QtCore.QSize(15, 30))

        self.left_close.setFixedSize(15, 15)  # 设置关闭按钮的大小
        self.left_visit.setFixedSize(15, 15)  # 设置按钮大小
        self.left_mini.setFixedSize(15, 15)  # 设置最小化按钮大小
        self.left_close.setStyleSheet(
            '''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}''')
        self.left_visit.setStyleSheet(
            '''QPushButton{background:#F7D674;border-radius:5px;}QPushButton:hover{background:yellow;}''')
        self.left_mini.setStyleSheet(
            '''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}''')
        self.left_set_tools_UI()

    def init_ui(self):
        self.setFixedSize(960, 700)
        self.main_widget = QtWidgets.QWidget()  # 创建窗口主部件
        self.main_layout = QtWidgets.QGridLayout()  # 创建主部件的网格布局
        self.main_widget.setLayout(self.main_layout)  # 设置窗口主部件布局为网格布局


        self.left_base_ui()
        self.right_base_ui()
        self.right_search_ui()
        self.setCentralWidget(self.main_widget)  # 设置窗口主部件

        self.setWindowOpacity(int(self.num)/10)  # 设置窗口透明度
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)  # 设置窗口背景透明
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)  # 隐藏边框
        self.main_layout.setSpacing(0)


    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.m_flag = True
            self.m_Position = event.globalPos() - self.pos()  # 获取鼠标相对窗口的位置
            event.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if Qt.LeftButton and self.m_flag:
            self.move(QMouseEvent.globalPos() - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))

